<template>
  <el-dialog
    v-model="visible"
    title="财务报表"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="report-container">
      <!-- 报表筛选条件 -->
      <div class="filter-section">
        <el-form :model="filterForm" inline>
          <el-form-item label="报表类型">
            <el-select v-model="filterForm.reportType" placeholder="请选择报表类型" style="width: 200px">
              <el-option label="收支汇总表" value="summary" />
              <el-option label="预算执行表" value="budget_execution" />
              <el-option label="月度财务表" value="monthly" />
              <el-option label="年度财务表" value="yearly" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 240px"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="generateReport">
              生成报表
            </el-button>
            <el-button @click="exportReport" :disabled="!reportData.length">
              导出报表
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 报表内容 -->
      <div class="report-content" v-if="reportData.length">
        <!-- 收支汇总表 -->
        <template v-if="filterForm.reportType === 'summary'">
          <div class="report-header">
            <h3>收支汇总表</h3>
            <p class="report-period">报表期间：{{ formatDateRange() }}</p>
          </div>
          
          <div class="summary-cards">
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="summary-card income">
                  <div class="card-header">
                    <el-icon><TrendCharts /></el-icon>
                    <span>总收入</span>
                  </div>
                  <div class="card-value">¥{{ formatAmount(summaryData.totalIncome) }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-card expense">
                  <div class="card-header">
                    <el-icon><Minus /></el-icon>
                    <span>总支出</span>
                  </div>
                  <div class="card-value">¥{{ formatAmount(summaryData.totalExpense) }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-card balance">
                  <div class="card-header">
                    <el-icon><Wallet /></el-icon>
                    <span>净收支</span>
                  </div>
                  <div class="card-value" :class="{ negative: summaryData.balance < 0 }">
                    ¥{{ formatAmount(summaryData.balance) }}
                  </div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="summary-card budget">
                  <div class="card-header">
                    <el-icon><DataAnalysis /></el-icon>
                    <span>预算执行率</span>
                  </div>
                  <div class="card-value">{{ summaryData.budgetExecutionRate }}%</div>
                </div>
              </el-col>
            </el-row>
          </div>

          <el-table :data="reportData" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="category" label="类别" width="120" />
            <el-table-column prop="type" label="类型" width="120" />
            <el-table-column prop="amount" label="金额" width="150">
              <template #default="{ row }">
                <span class="amount" :class="{ negative: row.amount < 0 }">
                  ¥{{ formatAmount(Math.abs(row.amount)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="count" label="笔数" width="100" />
            <el-table-column prop="percentage" label="占比" width="100">
              <template #default="{ row }">
                {{ row.percentage }}%
              </template>
            </el-table-column>
            <el-table-column prop="description" label="说明" />
          </el-table>
        </template>

        <!-- 预算执行表 -->
        <template v-if="filterForm.reportType === 'budget_execution'">
          <div class="report-header">
            <h3>预算执行表</h3>
            <p class="report-period">报表期间：{{ formatDateRange() }}</p>
          </div>

          <el-table :data="reportData" border style="width: 100%">
            <el-table-column prop="budgetItem" label="预算项目" width="200" />
            <el-table-column prop="budgetAmount" label="预算金额" width="150">
              <template #default="{ row }">
                <span class="amount">¥{{ formatAmount(row.budgetAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="actualAmount" label="实际支出" width="150">
              <template #default="{ row }">
                <span class="amount">¥{{ formatAmount(row.actualAmount) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="variance" label="差异" width="150">
              <template #default="{ row }">
                <span class="amount" :class="{ negative: row.variance < 0 }">
                  ¥{{ formatAmount(Math.abs(row.variance)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="executionRate" label="执行率" width="120">
              <template #default="{ row }">
                <el-progress
                  :percentage="row.executionRate"
                  :color="getProgressColor(row.executionRate)"
                  :stroke-width="8"
                />
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusTag(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </template>

        <!-- 月度/年度财务表 -->
        <template v-if="filterForm.reportType === 'monthly' || filterForm.reportType === 'yearly'">
          <div class="report-header">
            <h3>{{ filterForm.reportType === 'monthly' ? '月度' : '年度' }}财务表</h3>
            <p class="report-period">报表期间：{{ formatDateRange() }}</p>
          </div>

          <!-- 趋势图表 -->
          <div class="chart-section">
            <div class="chart-container" ref="chartContainer">
              <!-- 这里可以集成 ECharts 或其他图表库 -->
              <div class="chart-placeholder">
                <el-icon><TrendCharts /></el-icon>
                <p>收支趋势图表</p>
              </div>
            </div>
          </div>

          <el-table :data="reportData" border style="width: 100%; margin-top: 20px">
            <el-table-column prop="period" label="期间" width="120" />
            <el-table-column prop="income" label="收入" width="150">
              <template #default="{ row }">
                <span class="amount income">¥{{ formatAmount(row.income) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="expense" label="支出" width="150">
              <template #default="{ row }">
                <span class="amount expense">¥{{ formatAmount(row.expense) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="balance" label="净收支" width="150">
              <template #default="{ row }">
                <span class="amount" :class="{ negative: row.balance < 0 }">
                  ¥{{ formatAmount(Math.abs(row.balance)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="cumulativeBalance" label="累计余额" width="150">
              <template #default="{ row }">
                <span class="amount" :class="{ negative: row.cumulativeBalance < 0 }">
                  ¥{{ formatAmount(Math.abs(row.cumulativeBalance)) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="growthRate" label="增长率" width="120">
              <template #default="{ row }">
                <span :class="{ negative: row.growthRate < 0 }">
                  {{ row.growthRate > 0 ? '+' : '' }}{{ row.growthRate }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" />
          </el-table>
        </template>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <el-empty description="请选择报表类型和时间范围，然后点击生成报表" />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="printReport" :disabled="!reportData.length">
          打印报表
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { TrendCharts, Minus, Wallet, DataAnalysis } from '@element-plus/icons-vue'

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 响应式数据
const chartContainer = ref()
const reportData = ref<any[]>([])
const summaryData = ref({
  totalIncome: 0,
  totalExpense: 0,
  balance: 0,
  budgetExecutionRate: 0
})

const filterForm = reactive({
  reportType: 'summary',
  dateRange: [] as string[]
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 方法
const formatAmount = (amount: number | null | undefined): string => {
  if (amount === null || amount === undefined) return '0.00'
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}

const formatDateRange = (): string => {
  if (!filterForm.dateRange || filterForm.dateRange.length !== 2) {
    return '全部时间'
  }
  return `${filterForm.dateRange[0]} 至 ${filterForm.dateRange[1]}`
}

const getProgressColor = (percentage: number): string => {
  if (percentage < 50) return '#f56c6c'
  if (percentage < 80) return '#e6a23c'
  return '#67c23a'
}

const getStatusTag = (status: string): string => {
  const tagMap: Record<string, string> = {
    normal: 'success',
    warning: 'warning',
    over: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    normal: '正常',
    warning: '预警',
    over: '超支'
  }
  return textMap[status] || status
}

const generateReport = async () => {
  if (!filterForm.reportType) {
    ElMessage.warning('请选择报表类型')
    return
  }

  try {
    // 模拟API调用生成报表数据
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 根据报表类型生成不同的数据
    switch (filterForm.reportType) {
      case 'summary':
        generateSummaryReport()
        break
      case 'budget_execution':
        generateBudgetExecutionReport()
        break
      case 'monthly':
      case 'yearly':
        generatePeriodReport()
        break
    }
    
    ElMessage.success('报表生成成功')
  } catch (error) {
    ElMessage.error('报表生成失败')
  }
}

const generateSummaryReport = () => {
  // 模拟收支汇总数据
  summaryData.value = {
    totalIncome: 1250000,
    totalExpense: 980000,
    balance: 270000,
    budgetExecutionRate: 78.4
  }
  
  reportData.value = [
    {
      category: '收入',
      type: '水费收入',
      amount: 800000,
      count: 1200,
      percentage: 64.0,
      description: '居民和企业用水费用'
    },
    {
      category: '收入',
      type: '电费收入',
      amount: 350000,
      count: 800,
      percentage: 28.0,
      description: '水库发电收入'
    },
    {
      category: '收入',
      type: '政府补贴',
      amount: 100000,
      count: 4,
      percentage: 8.0,
      description: '政府运营补贴'
    },
    {
      category: '支出',
      type: '人员工资',
      amount: -450000,
      count: 24,
      percentage: 45.9,
      description: '员工薪资及福利'
    },
    {
      category: '支出',
      type: '设备维护',
      amount: -280000,
      count: 156,
      percentage: 28.6,
      description: '设备保养维修费用'
    },
    {
      category: '支出',
      type: '材料采购',
      amount: -180000,
      count: 89,
      percentage: 18.4,
      description: '维修材料及办公用品'
    },
    {
      category: '支出',
      type: '水电费',
      amount: -70000,
      count: 12,
      percentage: 7.1,
      description: '办公及运营用电费用'
    }
  ]
}

const generateBudgetExecutionReport = () => {
  reportData.value = [
    {
      budgetItem: '人员费用',
      budgetAmount: 500000,
      actualAmount: 450000,
      variance: 50000,
      executionRate: 90,
      status: 'normal',
      remark: '按计划执行'
    },
    {
      budgetItem: '设备维护费',
      budgetAmount: 300000,
      actualAmount: 280000,
      variance: 20000,
      executionRate: 93.3,
      status: 'normal',
      remark: '维护成本控制良好'
    },
    {
      budgetItem: '材料采购费',
      budgetAmount: 200000,
      actualAmount: 180000,
      variance: 20000,
      executionRate: 90,
      status: 'normal',
      remark: '采购成本节约'
    },
    {
      budgetItem: '运营费用',
      budgetAmount: 100000,
      actualAmount: 120000,
      variance: -20000,
      executionRate: 120,
      status: 'warning',
      remark: '超出预算，需要关注'
    },
    {
      budgetItem: '应急费用',
      budgetAmount: 50000,
      actualAmount: 65000,
      variance: -15000,
      executionRate: 130,
      status: 'over',
      remark: '应急支出较多'
    }
  ]
}

const generatePeriodReport = () => {
  const isMonthly = filterForm.reportType === 'monthly'
  const periods = isMonthly 
    ? ['2024-01', '2024-02', '2024-03', '2024-04', '2024-05', '2024-06']
    : ['2020', '2021', '2022', '2023', '2024']
  
  let cumulativeBalance = 0
  reportData.value = periods.map((period, index) => {
    const income = Math.floor(Math.random() * 200000) + 100000
    const expense = Math.floor(Math.random() * 150000) + 80000
    const balance = income - expense
    cumulativeBalance += balance
    
    const prevIncome = index > 0 ? reportData.value[index - 1]?.income || income : income
    const growthRate = ((income - prevIncome) / prevIncome * 100).toFixed(1)
    
    return {
      period,
      income,
      expense,
      balance,
      cumulativeBalance,
      growthRate: parseFloat(growthRate),
      remark: balance > 0 ? '盈余' : '亏损'
    }
  })
}

const exportReport = () => {
  // 模拟导出功能
  ElMessage.success('报表导出成功')
}

const printReport = () => {
  // 模拟打印功能
  window.print()
}

const handleClose = () => {
  visible.value = false
}
</script>

<style scoped>
.report-container {
  min-height: 500px;
}

.filter-section {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.report-header {
  text-align: center;
  margin-bottom: 20px;
}

.report-header h3 {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.report-period {
  color: #909399;
  font-size: 14px;
  margin: 0;
}

.summary-cards {
  margin-bottom: 20px;
}

.summary-card {
  padding: 20px;
  border-radius: 8px;
  color: white;
  text-align: center;
}

.summary-card.income {
  background: linear-gradient(135deg, #67c23a, #85ce61);
}

.summary-card.expense {
  background: linear-gradient(135deg, #f56c6c, #f78989);
}

.summary-card.balance {
  background: linear-gradient(135deg, #409eff, #66b1ff);
}

.summary-card.budget {
  background: linear-gradient(135deg, #e6a23c, #ebb563);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  opacity: 0.9;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
}

.card-value.negative {
  color: #f56c6c;
}

.amount {
  font-weight: 600;
}

.amount.income {
  color: #67c23a;
}

.amount.expense {
  color: #f56c6c;
}

.amount.negative {
  color: #f56c6c;
}

.negative {
  color: #f56c6c;
}

.chart-section {
  margin: 20px 0;
}

.chart-container {
  height: 300px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-progress-bar__outer) {
  border-radius: 4px;
}

:deep(.el-progress-bar__inner) {
  border-radius: 4px;
}
</style>